package com.lyf.service.user.Impl;

import com.alibaba.fastjson.JSONObject;
import com.lyf.constant.MessageConstant;
import com.lyf.dto.UserLoginDTO;
import com.lyf.mapper.user.UserMapper;
import com.lyf.pojo.User;
import com.lyf.properties.WeChatProperties;
import com.lyf.service.user.UserService;
import com.lyf.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    // 微信登录验证接口
    private static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    // 微信登录授权类型
    private static final String GRANT_TYPE = "authorization_code";
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;

    /**
     * 微信登录
     * @return
     */
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        // 调用微信接口，获取当前用户openid
        String openid = getOpenId(userLoginDTO.getCode());
        // 判斷openid是否存在，空则抛出异常
        if (openid == null)
            throw new RuntimeException(MessageConstant.LOGIN_FAILED);
        // 判斷是否为新用户
        User user = userMapper.getByOpenid(openid);

        // 是新用户，则创建用户并插入数据
        if (user == null){
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }

        // 返回用户信息
        return user;
    }

    private String getOpenId(String code){
        // 调用微信接口，获取当前用户openid
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", code);
        paramMap.put("grant_type", GRANT_TYPE);
        String json= HttpClientUtil.doGet(WX_LOGIN, paramMap);

        JSONObject jsonObject = JSONObject.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;
    }

}
